import React, { useEffect, useState } from 'react';
import Modals from '@/components/modals/Modals';
import { Form, ModalProps } from 'antd';
import modelService from '@/api/services/modelService';
import { GetDefaultListRes, GetModelListRes } from '@/common/types';
import CascaderTag from '@/components/Antd/CascaderTag';
import { CircleLoading } from '@/components/loading';

interface Props extends ModalProps {
  open: boolean;
  onCancel: () => void;
  onOk: () => void;
  defaultList?: GetDefaultListRes;
  onClose?: () => void;
}

const index = ({ onOk, defaultList, onClose, ...props }: Props) => {
  const [chatList, setChatList] = useState<any>();
  const [embeddingList, setEmbeddingList] = useState<any>();
  const [funcCallList, setFuncCallList] = useState<any>();
  const [rerank, setRerank] = useState<any>();
  const [initLoading, setInitLoading] = useState<boolean>(false);

  const [form] = Form.useForm();

  useEffect(() => {
    if (defaultList && props.open) {
      init();
    }
  }, [defaultList, props.open]);

  const init = () => {
    setInitLoading(true);
    modelService
      .getModelList({
        offset: -1,
        page: 1,
        pageSize: 9999999,
        searchText: '',
      })
      .then((res) => {
        // 获取列表
        const chat = buildTree(res, 'llm');
        const embedding = buildTree(res, 'embedding');
        const funcCall = buildTree(res, 'funcCall', true);
        const rerank = buildTree(res, 'rerank');

        // 存入值
        setChatList(chat);
        setEmbeddingList(embedding);
        setFuncCallList(funcCall);
        setRerank(rerank);

        form.setFieldsValue({
          chat: filterValue(chat, defaultList?.chat?.id),
          funcCall: filterValue(funcCall, defaultList?.funcCall?.id),
          embedding: filterValue(embedding, defaultList?.embedding?.id),
          rerank: filterValue(rerank, defaultList?.rerank?.id),
        });

        // 格式化Form
        // form.setFieldsValue({
        //   chat: filterValue(chat, defaultList?.find((item) => item.type === 'chat')?.id),
        //   funcCall: filterValue(
        //     funcCall,
        //     defaultList?.find((item) => item.type === 'funcCall')?.id,
        //   ),
        //   embedding: filterValue(
        //     embedding,
        //     defaultList?.find((item) => item.type === 'embedding')?.id,
        //   ),
        //   rerank: filterValue(rerank, defaultList?.find((item) => item.type === 'rerank')?.id),
        // });
      })
      .finally(() => {
        setInitLoading(false);
      });
  };

  const filterValue = (data: any, id?: string): string[] => {
    if (!id) return [];

    const result = [];
    for (let i = 0; i < data.length; i++) {
      const item = data[i];
      for (let j = 0; j < item.children.length; j++) {
        if (item.children[j].value === id) {
          result.push(item.value);
          result.push(item.children[j].value);
        }
      }
    }
    return result;
  };

  const buildTree = (data: GetModelListRes, key: string, bol: boolean = false) => {
    const tree = {};
    // 遍历数据并按 provider 分组
    data.list.map((item) => {
      const { provider, modelType, id, usedInToolCall } = item;

      if (!tree[provider]) {
        tree[provider] = {
          value: id,
          label: provider,
          children: [],
        };
      }

      if (bol) {
        if (modelType === key || (modelType === 'llm' && usedInToolCall)) {
          const { name, isRecommend, id, isConnect } = item;
          tree[provider].children.push({
            value: id,
            label: name,
            isRecommend,
            isConnect,
          });
        }
      } else {
        if (modelType === key) {
          const { name, isRecommend, id, isConnect } = item;
          tree[provider].children.push({
            value: id,
            label: name,
            isRecommend,
            isConnect,
          });
        }
      }
    });

    // 过滤掉没有 children 的 provider
    const filteredTree = Object.values(tree).filter((node) => node.children.length > 0);

    // 返回树形格式的数组
    return filteredTree;
  };

  const filter = (inputValue: string, path: any[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  const onSubmit = (value: any) => {
    const arr = [];

    if (!checkList(value, 'chat')) {
      arr.push(
        modelService.updateModel(value.chat[value.chat.length - 1], {
          isActive: true,
          default: 'chat',
        }),
      );
    }

    if (!checkList(value, 'funcCall')) {
      arr.push(
        modelService.updateModel(value.funcCall[value.funcCall.length - 1], {
          isActive: true,
          default: 'funcCall',
        }),
      );
    }

    if (!checkList(value, 'embedding')) {
      arr.push(
        modelService.updateModel(value.embedding[value.embedding.length - 1], {
          isActive: true,
          default: 'embedding',
        }),
      );
    }
    if (!checkList(value, 'rerank')) {
      arr.push(
        modelService.updateModel(value.rerank[value.rerank.length - 1], {
          isActive: true,
          default: 'rerank',
        }),
      );
    }

    if (arr.length > 0) {
      Promise.all(arr)
        .then((res) => {
          onOk();
          console.log(res);
        })
        .catch((e) => {
          console.log(e);
        });
      return;
    }

    onOk();
  };

  const checkList = (value: any, key: string) => {
    if (!defaultList) return false;

    if (defaultList[key]) {
      return defaultList[key].id === value[key][value[key].length - 1];
    } else {
      return false;
    }

    // const defaultValue = defaultList?.find((item) => item.type === key);

    // if (!defaultValue) {
    //   return false;
    // }

    // const valueId = value[key][value[key].length - 1];
    // return valueId === defaultValue.id;
  };

  return (
    <Modals title="默认模型配置" onOk={form.submit} {...props} okText="保存" onClose={onClose}>
      {initLoading ? (
        <div className="h-80 w-full">
          <CircleLoading />
        </div>
      ) : (
        <Form className="flex flex-col gap-6" form={form} onFinish={onSubmit} layout="vertical">
          <Form.Item
            className="w-full"
            label={
              <div className="flex gap-1">
                <div className="header text-sm leading-[22px] text-text-4">语言模型</div>
                <div className="text-xs leading-5 text-text-3">
                  智能体的“大脑”，负责理解和回答问题。
                </div>
              </div>
            }
            style={{ marginBottom: 0 }}
            name={'chat'}
            rules={[{ required: true, message: '请选择语言模型' }]}
          >
            <CascaderTag
              options={chatList}
              placeholder="请选择语言模型"
              showSearch={{ filter }}
              // style={{
              //   width: 328,
              // }}
            />
          </Form.Item>
          <Form.Item
            label={
              <div className="flex gap-1">
                <div className="header text-sm leading-[22px] text-text-4">工具调用模型</div>
                <div className="text-xs leading-5 text-text-3">
                  让智能体学会使用工具或插件来完成任务。
                </div>
              </div>
            }
            className="w-full"
            name={'funcCall'}
            style={{ marginBottom: 0 }}
            rules={[{ required: true, message: '请选择工具调用模型' }]}
          >
            <CascaderTag
              options={funcCallList}
              placeholder="请选择工具调整"
              showSearch={{ filter }}
              // style={{
              //   width: 328,
              // }}
            />
          </Form.Item>
          <Form.Item
            label={
              <div className="flex gap-1">
                <div className="header text-sm leading-[22px] text-text-4">索引模型</div>
                <div className="text-xs leading-5 text-text-3">
                  让智能体能调用你本地的文档资料。
                </div>
              </div>
            }
            className="w-full"
            name={'embedding'}
            style={{ marginBottom: 0 }}
            rules={[{ required: true, message: '请选择索引模型' }]}
          >
            <CascaderTag
              options={embeddingList}
              placeholder="请选择索引模型"
              showSearch={{ filter }}
              // style={{
              //   width: 328,
              // }}
            />
          </Form.Item>
          <Form.Item
            label={
              <div className="flex gap-1">
                <div className="header text-sm leading-[22px] text-text-4">重排模型</div>
                <div className="text-xs leading-5 text-text-3">多个答案中选出最合适的那个</div>
              </div>
            }
            className="w-full"
            name={'rerank'}
            style={{ marginBottom: 0 }}
            rules={[{ required: true, message: '请选择重排模型' }]}
          >
            <CascaderTag
              options={rerank}
              placeholder="请选择重排模型"
              showSearch={{ filter }}
              // style={{
              //   width: 328,
              // }}
            />
          </Form.Item>
        </Form>
      )}
    </Modals>
  );
};

export default index;
